/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"fmt"
	wxcard "github.com/chanxuehong/wechat/mp/card"
	wxacitveuserform "github.com/chanxuehong/wechat/mp/card/membercard/activateuserform"
	wxcardqr "github.com/chanxuehong/wechat/mp/card/qrcode"
	"github.com/chanxuehong/wechat/mp/card/testwhitelist"
	"github.com/mjiulee/lego"
	"saas_sys_base/common"
	. "saas_sys_base/modules/merchantCard/models"
	. "saas_sys_base/modules/merchantCard/service/WxCard_service"
)

type MchCardApiService struct {
	wxCardService WxCardService
	mchMemberCardService MchMemberCardService
	mchUserMemberCardService MchUserMemberCardService
	memberCardAccountLogService MemberCardAccountLogService
}

/*
	// 卡券类型
	CardTypeGeneralCoupon = "GENERAL_COUPON" // 优惠券
	CardTypeGroupon       = "GROUPON"        // 团购券
	CardTypeCash          = "CASH"           // 代金券
	CardTypeDiscount      = "DISCOUNT"       // 折扣券
	CardTypeGift          = "GIFT"           // 礼品券
	CardTypeMemberCard    = "MEMBER_CARD"    // 会员卡
	CardTypeMeetingTicket = "MEETING_TICKET" // 会议门票
	CardTypeScenicTicket  = "SCENIC_TICKET"  // 景区门票
	CardTypeMovieTicket   = "MOVIE_TICKET"   // 电影票
	CardTypeBoardingPass  = "BOARDING_PASS"  // 飞机票

各种卡的核销规则

代金券：10元代金券，满十元可用，（满减）
折扣券：9折券，满百折扣          （满折）
优惠券（满减+满折）
团购券：出示抵消本次消费

特殊票券
会议、演出门票
景区门票
电影票
飞机票
(t *WxCardApiService) ConsumeCardByWho(appwho common.Who)
*/

func (t *MchCardApiService) CreateCardByWho(who *common.Who, card *MchCardUnionMsg) (*MchMemberCard, error) {

	err := CheckMchCardMsg(card)
	if err != nil {
		return nil, err
	}

    if card.CardMode == CARD_MODE_WECHAT || card.CardMode == CARD_MODE_MCH_WECHAT {
		_, _, err := t.wxCardService.CreateCardByWho(who, &card.Card) //这里card也是一个输出参数
		if err != nil {
			return nil, err
		}
	}

	mchMembercard, err := t.mchMemberCardService.CreateCardByWho(who, card)
	if err != nil {
		return nil, err
	}

	return mchMembercard, err
}

func (t *MchCardApiService) UpgradeCardModeToWxCardByWho(who *common.Who, card *MchCardUnionMsg) (*MchMemberCard, error) {
	if card.CardMode == CARD_MODE_WECHAT || card.CardMode == CARD_MODE_MCH_WECHAT {
		_, _, err := t.wxCardService.CreateCardByWho(who, &card.Card)
		if err != nil {
			return nil, err
		}
	}

	mchMemberCard, err := t.mchMemberCardService.CreateCardByWho(who, card)
	if err != nil {
		return nil, err
	}

	return mchMemberCard, err
}


func (t *MchCardApiService) BatchGetByWho(who *common.Who, page, psize int) (result []MchMemberCard, total int64, err error) {
	result, total, err = t.mchMemberCardService.BatchGetByWho(who, page, psize)
	if err != nil {
		return nil, 0, err
	}
	return result, total, nil
}

//TODO GetCardByWho()的返回参数MchCardMemberCard代表会员卡，有可能这个接口可以返回非会员卡种类的卡（如优惠券），
//以后再使用多态的类型来包含会员卡和优惠券等多种类的卡，目前先这样
func (t *MchCardApiService) GetCardByWho(who *common.Who, MchCardId int64) (*MchMemberCard, error) {
	mchMemberCard, err := t.mchMemberCardService.GetCardByWho(who, MchCardId)
	if err != nil {
		return nil, err
	}
	return mchMemberCard, err
}

//投放
func (t *MchCardApiService) CreateQrCodeByWho(appwho common.Who, createReqPara *wxcardqr.CreateQrCodeReqPara) (result *wxcardqr.QrcodeInfo, err error) {

	return result, err
}

//白名单
//投放
func (t *MchCardApiService) TestWhileListByWho(appwho common.Who, para *testwhitelist.SetParameters) (err error) {


	return err
}

func (t *MchCardApiService) SetActivateUserForm(who common.Who, userform *wxacitveuserform.ActiveuserFormPara) (err error) {

	return err
}

//领卡
func (t *MchCardApiService) FetchCardByWho(who *common.Who, MchCardId int64, memberInfo *MemberInfo) (*MchUserMemberCard, error) {
	memberCard, err := t.GetCardByWho(who, MchCardId)
	if err != nil { //卡存在
		return nil, err
	}

	memberCard = memberCard //卡存在

	retMchUserMemberCard, err := t.mchUserMemberCardService.CardGetCardEventHandlerForMchCard(who, "", MchCardId, nil, memberInfo)
	if err != nil {
		return nil, err
	}

	return retMchUserMemberCard, nil
}

// Depression
/*func (t *MchCardApiService) CardGetCardEventHandler(weappid string, mixedMsg *core.MixedMsg, cardType string) (*MchCardUserCard, error) {
	if cardType == CARD_MODE_MCH {
		t.mchCardService.CardGetCardEventHandler(weappid, mixedMsg)
	} else if cardType == CARD_MODE_MCH_WECHAT || cardType == CARD_MODE_WECHAT {
		t.wxCardService.CardGetCardEventHandler(weappid, mixedMsg)
	}
    return nil, nil
}*/

//CreateCard2
/*
此创建卡接口的逻辑为：
如果为新创建卡，使用默认卡参数和会员卡等级配置，创建一张新的卡
如果同一租户已经存在卡了，不需要再创建一张卡,只需更新卡等级参数
 */

func (t *MchCardApiService) CreateCard2ByWho(who *common.Who, mchCardId int64, MemberLevelConf *MemberLevelConf, cardParaTemplId int) (*MchMemberCard, error) {
	/*count, err := t.mchCardService.CountByWhoAndCardType(who, wxcard.CardTypeMemberCard)
	if err != nil {
		return "", nil, nil, err
	}

	//此接口处理函数一个租户只能创建一张卡（带多个等级）
	if count > 1 {
		return "", nil, nil, errors.New("only one card per tenant")
	}

	 */

    if MemberLevelConf.LevelNo < 0 || MemberLevelConf.LevelNo >= MAX_MEMBERCARD_LEVEL {
		return nil, fmt.Errorf("member level no can not great than %d", MAX_MEMBERCARD_LEVEL)
	}


	//TODO 这里要加一个分布式锁
	//如果输入卡ID为0，则进入创建流程，如果为非0，则进入追加流程
    redislock, isLockSuccess, err := lego.TryLock("create_member_card")
    if err != nil{
    	return nil, err
	}

	if !isLockSuccess {
		return nil, fmt.Errorf("The only one person can creat card at the same time, (isLockSuccess<%d>)", isLockSuccess)
	}
	defer redislock.Unlock()

	if mchCardId == 0 {
		mchMemberCard := t.mchMemberCardService.GetMchMemberCardByWho(who)
		if mchMemberCard != nil {
			return nil, errors.New("only one card per tenant")
		}

		mchCardMsg := NewMchCardUnionMsg(wxcard.CardTypeMemberCard)
		mchCardMsg.MchMemberCard.MemberLevelConf[MemberLevelConf.LevelNo] = MemberLevelConf
		newCardMsg, err := GetCardParaByTempate_1000(mchCardMsg)
		if err != nil {
			return nil, err
		}

		mchMemberCard, err = t.CreateCardByWho(who, newCardMsg)
		return mchMemberCard, err
	} else {
		//mchMemberCard := t.mchMemberCardService.GetMchCardMemberCardByByWhoAndCardType(who, wxcard.CardTypeMemberCard)
		//newMemberCard := new(MchCardMemberCard)
		//newMemberCard.MemberLevelConf[LevelNo] = *MemberLevelConf
		rcMchMemberCard := t.mchMemberCardService.GetMchMemberCardById(mchCardId)
		if rcMchMemberCard == nil {
			return nil, fmt.Errorf("Not found mch card id <%d>", mchCardId)
		}

		/*if rcMemberCard.MemberLevelConf == nil {TODO 如果创建卡的时候，没有分配MemberLevelConf空间，会造成MemberLevelConf为nil
			rcMemberCard.MemberLevelConf = make([]*MemberLevelConf, MAX_MEMBERCARD_LEVEL)
		} */
		rcMchMemberCard.MemberLevelConf[MemberLevelConf.LevelNo] = MemberLevelConf

		isSuccess := t.mchMemberCardService.UpdateMchMemberCard(rcMchMemberCard)
		if !isSuccess {
			return nil, errors.New("only one card per tenant")
		}
		return rcMchMemberCard, nil
	}


}

func (t *MchCardApiService) UpdateMemberCard2ByWho(who *common.Who, mchCardId int64, MemberLevelConf *MemberLevelConf) (*MchMemberCard, error) {
	/*count, err := t.mchCardService.CountByWhoAndCardType(who, wxcard.CardTypeMemberCard)
	if err != nil {
		return "", nil, nil, err
	}

	//此接口处理函数一个租户只能创建一张卡（带多个等级）
	if count > 1 {
		return "", nil, nil, errors.New("only one card per tenant")
	}

	*/

	if MemberLevelConf.LevelNo < 0 || MemberLevelConf.LevelNo >= MAX_MEMBERCARD_LEVEL {
		return nil, fmt.Errorf("member level no can not great than %d", MAX_MEMBERCARD_LEVEL)
	}

	if mchCardId == 0 {
		return nil, errors.New("mchCardId must be non-zero when update member card")
	}

	{
		rcMchMemberCard := t.mchMemberCardService.GetMchMemberCardById(mchCardId)
		if rcMchMemberCard == nil {
			return nil, fmt.Errorf("Not found mch card id <%d>", mchCardId)
		}

		rcMchMemberCard.MemberLevelConf[MemberLevelConf.LevelNo] = MemberLevelConf

		isSuccess := t.mchMemberCardService.UpdateMchMemberCard(rcMchMemberCard)
		if !isSuccess {
			return nil, errors.New("only one card per tenant")
		}
		return rcMchMemberCard, nil
	}


}

func (t *MchCardApiService) CreateMemberCardDetailByWho(who *common.Who, mchCardId int64) (*MchMemberCard, error) {
	rcCard := t.mchMemberCardService.GetMchMemberCardById(mchCardId)
	if rcCard == nil {
		return nil, fmt.Errorf("Not found mch card id <%d>", mchCardId)
	}


	return rcCard, nil
}

/*
func (t *MchCardApiService) FetchUserMemberCard(who *common.Who, mchCardId int64) (mchCard *MchCard, mchmembercard *MchCardMemberCard, err error) {
	rcCard := t.mchMemberCardService.GetMchMemberCardById(mchCardId)
	if rcCard == nil {
		return nil, nil, fmt.Errorf("Not found mch card id <%d>", mchCardId)
	}
	rcMemberCard := t.mchMemberCardService.GetMchCardMemberCardByMchCardId(mchCardId)
	//:rcMemberCard.MemberLevelConf[LevelNo] = *MemberLevelConf
	if rcMemberCard == nil {
		return nil, nil, fmt.Errorf("Not found mch card id <%d>", mchCardId)
	}

	return rcCard, rcMemberCard, nil
}*/

func (t *MchCardApiService) ListMemberCardByWho(who *common.Who, page, psize int) ([]MchMemberCard, int64, error) {
	list, total, err := t.mchMemberCardService.ListMemberCardByWho(who, page, psize)
	if err != nil {
		return nil, 0, err
	}

	return list, total, nil
}

func (t *MchCardApiService) DelCard(cardId int64) (error) {
	isSuccess := t.mchMemberCardService.SDelMchMemberCardById(cardId) // TODO这里需要删除mch card表和mch member card的记录（目前仅删除一个表的记录）
	if !isSuccess {
		return fmt.Errorf("del mchCardId<%d> err", cardId)
	}

	return nil
}

//addBalance为内部接口，需要外部调用者配置BusinessType
func (t *MchCardApiService) addBalance(userWho *common.Who, userCardId int64, balanceAddend CardAddBalance) error {
	return t.mchUserMemberCardService.AddBalance(userWho, userCardId, balanceAddend)
}

func (t *MchCardApiService) ListMchUserMemberCardByTenant(tid int64, keyword string, orderfiled, order string, page, psize int, ) ([]MchUserMemberCard, int64, error) {
	return t.mchUserMemberCardService.ListMchUserMemberCardByTenant(tid, keyword, orderfiled, order, page, psize, )
}

func (t *MchCardApiService) GetMchUserMemberCardById(id int64) *MchUserMemberCard {
	return t.mchUserMemberCardService.GetMchUserMemberCardById(id)
}

func (t *MchCardApiService) GetMchMemberCardById(id int64) *MchMemberCard {
	return t.mchMemberCardService.GetMchMemberCardById(id)
}

func (t *MchCardApiService) MchModifyBalance(userWho *common.Who, userCardId int64, balanceAddend CardAddBalance) error {
	return t.mchUserMemberCardService.AddBalance(userWho, userCardId, balanceAddend)
}

func (t *MchCardApiService) DelUserCard(userCardId int64) (error) {
	isSuccess := t.mchUserMemberCardService.DelMchUserMemberCardById(userCardId) // TODO这里需要删除mch card表和mch member card的记录（目前仅删除一个表的记录）
	if !isSuccess {
		return fmt.Errorf("del userCardId<%d> err", userCardId)
	}

	return nil
}

func (t *MchCardApiService) ListMemberCardAccountLogByUserCardId(userCardId int64, bussinessType []BusinessType,pageparam common.PageParam)([]MemberCardAccountLog, int64, error)  {
	return t.memberCardAccountLogService.ListMemberCardAccountLogByUserCardId(userCardId, bussinessType,pageparam)
}

func (t *MchCardApiService) UpdateMemberInfo(who *common.Who, userCardId int64, memberInfo *MemberInfo)(error)  {
	return t.mchUserMemberCardService.UpdateMemberInfo(who, userCardId, memberInfo)
}

func (t *MchCardApiService) MchModifyUserCardBalance(userWho *common.Who, userCardId int64, balanceAddend CardAddBalance) error {
	balanceAddend.BusinessType = BusinessType_MchRechargeForUser
	balanceAddend.IncomeType = IncomeType_In
	return t.mchUserMemberCardService.AddBalance(userWho, userCardId, balanceAddend)
}
